package com.littlerpc.protocol.net.jetty.server;

import com.littlerpc.protocol.codec.Serializer;
import com.littlerpc.protocol.net.common.RpcServer;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.thread.ExecutorThreadPool;

/**
 *
 * @author ChengPeng
 * @date 2017/7/14
 */
public class JettyServer extends RpcServer {
    public JettyServer(int port, Serializer serializer) {
        super(port, serializer);
    }

    private Server server ;

    @Override
    public void start() {

        Thread serverThread = new Thread(() -> {
            //创建一个jettyserver
            server = new Server(new ExecutorThreadPool(200, 200, 30000));
            // handler
            HandlerCollection handlerc =new HandlerCollection();
            handlerc.setHandlers(new Handler[]{/*new JettyServerHandler(serializer)*/});
            server.setHandler(handlerc);
            // connector
            ServerConnector connector=new ServerConnector(server);
            connector.setPort(port);
            server.setConnectors(new Connector[] { connector });

            try {
                server.start();
                System.out.println("jetty启动。。。。。。。");
                server.join();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                server.destroy();
            }

        });

        serverThread.setDaemon(true);
        serverThread.start();


    }

    @Override
    public void stop() {
        if (server != null) {
            try {
                server.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
